package cn.edu.ytu.edroid.easychart;

import java.util.ArrayList;
import java.util.List;

import cn.edu.ytu.edroid.easychart.R;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class EditActivity extends ListActivity {

	static final String TAG = "EasyChart";

	private String cht;

	private static final String[] chartTypes = { "PieChart", "BarChart",
			"LineChart", "SparkLine", "RadarChart", "QrCode", "GoogleOMeter" };
	private Spinner spinnerChartType;
	private Spinner spinnerChartOption;

	private ArrayAdapter<String> chartTypeAdapter;
	private ArrayAdapter<String> chartOptionAdapter;

	List<EventDatum> dataList = new ArrayList<EventDatum>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_activity);

		spinnerChartType = (Spinner) findViewById(R.id.spinner_chart_type);
		// 将可选内容与ArrayAdapter连接
		chartTypeAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, chartTypes);

		chartOptionAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item);

		// 设置下拉列表的风格
		chartTypeAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 将chartTypeAdapter添加到spinnerChartType中
		spinnerChartType.setAdapter(chartTypeAdapter);
		// 添加spinnerChartType事件监听
		spinnerChartType
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						// TODO Auto-generated method stub
						spinnerChartOption = (Spinner) findViewById(R.id.spinner_chart_option);

						switch (position) {
						case 0:
							findViewById(R.id.datum_value_text)
									.setVisibility(0);
							findViewById(R.id.datum_value_field).setVisibility(
									0);
							chartOptionAdapter.clear();
							chartOptionAdapter.add("2D");
							chartOptionAdapter.add("3D");
							spinnerChartOption.setAdapter(chartOptionAdapter);
							spinnerChartOption.setVisibility(0);

							spinnerChartOption
									.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

										@Override
										public void onItemSelected(
												AdapterView<?> parent,
												View view, int position, long id) {
											// TODO Auto-generated method stub
											if (position == 0) {
												cht = "p";
											} else if (position == 1) {
												cht = "p3";
											}
										}

										@Override
										public void onNothingSelected(
												AdapterView<?> parent) {
											// TODO Auto-generated method stub

										}
									});
							break;

						case 1:
							findViewById(R.id.datum_value_text)
									.setVisibility(0);
							findViewById(R.id.datum_value_field).setVisibility(
									0);
							chartOptionAdapter.clear();
							chartOptionAdapter.add("Horizontal");
							chartOptionAdapter.add("Vertical");
							spinnerChartOption.setAdapter(chartOptionAdapter);
							spinnerChartOption.setVisibility(0);

							spinnerChartOption
									.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

										@Override
										public void onItemSelected(
												AdapterView<?> parent,
												View view, int position, long id) {
											// TODO Auto-generated method stub
											if (position == 0) {
												cht = "bhs";
											} else if (position == 1) {
												cht = "bvs";
											}
										}

										@Override
										public void onNothingSelected(
												AdapterView<?> parent) {
											// TODO Auto-generated method stub

										}
									});
							break;
						case 2:
							cht = "lc";
							findViewById(R.id.datum_value_text)
									.setVisibility(0);
							findViewById(R.id.datum_value_field).setVisibility(
									0);
							spinnerChartOption.setVisibility(4);
							chartOptionAdapter.clear();
							break;
						case 3:
							cht = "ls";
							findViewById(R.id.datum_value_text)
									.setVisibility(0);
							findViewById(R.id.datum_value_field).setVisibility(
									0);
							spinnerChartOption.setVisibility(4);
							chartOptionAdapter.clear();
							break;
						case 4:
							cht = "r";
							findViewById(R.id.datum_value_text)
									.setVisibility(0);
							findViewById(R.id.datum_value_field).setVisibility(
									0);
							spinnerChartOption.setVisibility(4);
							chartOptionAdapter.clear();
							break;
						case 5:
							cht = "qr";
							findViewById(R.id.datum_value_text)
									.setVisibility(4);
							findViewById(R.id.datum_value_field).setVisibility(
									4);
							spinnerChartOption.setVisibility(4);
							chartOptionAdapter.clear();
							break;
						case 6:
							cht = "gm";
							findViewById(R.id.datum_value_text)
									.setVisibility(0);
							findViewById(R.id.datum_value_field).setVisibility(
									0);
							spinnerChartOption.setVisibility(4);
							chartOptionAdapter.clear();
							break;
						}

					}

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
						// TODO Auto-generated method stub

					}

				});

		final InputMethodManager input = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		final EditText datumValue = (EditText) findViewById(R.id.datum_value_field);
		final EditText datumTag = (EditText) findViewById(R.id.datum_tag_field);

		findViewById(R.id.button_add_datum).setOnClickListener(
				new OnClickListener() {
					public void onClick(View v) {
						EventDatum eventDatum = new EventDatum();

						String value = datumValue.getText().toString();
						String tag = datumTag.getText().toString();
						if (value.length() > 0) {
							eventDatum.value = Float.parseFloat(value);
						}
						eventDatum.tag = tag;

						dataList.add(eventDatum);
						((BaseAdapter) getListView().getAdapter())
								.notifyDataSetChanged();
						datumValue.setText("");
						datumTag.setText("");
					}
				});

		datumValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					input.hideSoftInputFromWindow(v.getWindowToken(), 0);
				}
			}
		});

		findViewById(R.id.button_clear_list).setOnClickListener(
				new OnClickListener() {
					public void onClick(View v) {
						int i = dataList.size();
						dataList.clear();
						((BaseAdapter) getListView().getAdapter())
								.notifyDataSetChanged();

						// DatabaseStoredData database = new
						// DatabaseStoredData(InputDatasetActivity.this);
						// int deleted_count = database.deleteAllData();
						Toast.makeText(EditActivity.this,
								"Deleted " + i + " records.",
								Toast.LENGTH_SHORT).show();
					}
				});

		findViewById(R.id.button_chart).setOnClickListener(
				new OnClickListener() {
					public void onClick(View v) {
						if (dataList.size() == 0) {
							Toast.makeText(EditActivity.this,
									"need 1 record at least",
									Toast.LENGTH_SHORT).show();
						} else if (cht.equals("qr") && dataList.size() > 1) {
							Toast.makeText(EditActivity.this,
									"QrCode needs only 1 tag",
									Toast.LENGTH_LONG).show();
						} else if (cht.equals("qr")
								&& dataList.get(0).tag.equals("")) {
							Toast.makeText(EditActivity.this,
									"the tag should not be empty",
									Toast.LENGTH_LONG).show();
						} else {

							ChartAction ca = new ChartAction(dataList, cht);

							/*
							 * Toast.makeText(EditActivity.this,
							 * ca.convertToUrl(), Toast.LENGTH_SHORT) .show();
							 */
							Intent intent = new Intent();
							intent.putExtra("url", ca.convertToUrl());
							intent.setClass(EditActivity.this,
									ChartActivity.class);

							startActivity(intent);
						}
					}
				});

		setListAdapter(new SimpleEventAdapter(this));

		final StateObject state = (StateObject) getLastNonConfigurationInstance();
		if (state != null) {

			this.dataList = state.dataList;
			SimpleEventAdapter sea = (SimpleEventAdapter) getListView()
					.getAdapter();
			sea.notifyDataSetChanged();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.edit_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.about:
			new AlertDialog.Builder(EditActivity.this).setTitle("About")
					.setMessage(R.string.about).setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
								}
							}).create().show();
			break;
		case R.id.exit:
			finish();
			break;
		}
		return false;
	}

	class StateObject {
		List<EventDatum> dataList;
	}

	@Override
	public Object onRetainNonConfigurationInstance() {

		StateObject state = new StateObject();
		state.dataList = this.dataList;

		return state;
	}

	public static class EventDatum {
		public float value;
		public String tag;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		dataList.remove(position);
		((BaseAdapter) getListView().getAdapter()).notifyDataSetChanged();

	}

	class SimpleEventAdapter extends BaseAdapter {

		Context context;
		private LayoutInflater mInflater;

		SimpleEventAdapter(Context context) {
			this.context = context;
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return dataList.size();
		}

		@Override
		public Object getItem(int position) {
			return dataList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public class ViewHolderEvent {
			public TextView tag, value;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolderEvent holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_item_event, null);

				// Creates a ViewHolder and store references to the two children
				// views
				// we want to bind data to.
				holder = new ViewHolderEvent();
				holder.value = (TextView) convertView
						.findViewById(R.id.datum_value);
				holder.tag = (TextView) convertView
						.findViewById(R.id.datum_tag);
				convertView.setTag(holder);

			} else {

				// Get the ViewHolder back to get fast access to the TextView
				// and the ImageView.
				holder = (ViewHolderEvent) convertView.getTag();
			}

			EventDatum event = (EventDatum) dataList.get(position);
			if (cht.equals("qr")) {
				holder.value.setText("no." + (position + 1));
				holder.tag.setText("\tTag: " + event.tag);
			} else {
				holder.value.setText("no." + (position + 1) + "\tValue: "
						+ event.value);
				holder.tag.setText("\tTag: " + event.tag);
			}
			return convertView;
		}
	}

}
